const PACKAGE_NAME = "com.yiqunkeji.yqlyz";
const SKIP_BUTTON = "':id/tt_splash_skip_btn'";

let storage = storages.create("PIG");

//检测无障碍模式是否启用
auto.waitFor();

//保持屏幕常量
device.keepScreenOn();

run();

console.show();

function run() {
    while (true) {
        try {
            killApp();
            countDown();
            start();
        } catch (e) {
            outputMessage(e);
            sleep(4000);
        }
    }
}

function start() {
    app.launchPackage(PACKAGE_NAME);
    sleep(15000);

    let ret = checkExistsById(':id/fl_defense');
    if (!ret) throw new Error('场景错误');

    let last = storage.get('current');
    let current = new Date().getTime();
    current = current / 1000;

    if (last != undefined) {
        let diff = current - last;
        if (diff >= 3000) {
            storage.put('current', current);
            //去合成
            merge();
        } else {
            enterGroup();
        }
    } else {
        //去抢红包
        enterGroup();
    }
}

/**
 * 群聊中心操作
 */
function enterGroup() {
    let redPack = idEndsWith(':id/text1').findOnce();
    if (!redPack) throw new Error('找不到红包按钮');
    let redRect = redPack.bounds();
    coordinateClick(redRect.centerX(), redRect.centerY(), 3500);

    let groups = textMatches(/(.*群聊.*)/).findOnce();
    if (!groups) throw new Error('找不到群聊场景');

    let talkGroups = className('android.widget.LinearLayout').find();
    for (let i = 0; i < talkGroups.length; i++) {
        let talk = talkGroups[i];
        let talkChild = talk.children();
        let isGroup = false; //是否是聊天群
        for (let j = 0; j < talkChild.length; j++) {
            let child = talkChild[j];
            let childText = child.text();
            if (childText != null && childText.indexOf("群") != -1) {
                isGroup = true;
            }
        }
        //群内操作
        if (isGroup) {
            let talkRect = talk.bounds();
            click(talkRect.centerX(), talkRect.centerY());
            sleep(3500);
            //获取红包列表
            for (let i = 0; i < 20; i++) {
                takeRedPack(1);
                swipePage();
                swipePage();
            }
            back();
            sleep(3500);
        }
    }

}

function watchVideoAndTakePack(document) {
    let rect = document.bounds();
    coordinateClick(rect.centerX(), rect.centerY(), 3500);
    let open = idEndsWith(':id/btn_open').findOne(5000);
    if (!open) throw new Error('找不到开红包按钮');
    let openRect = open.bounds();
    coordinateClick(openRect.centerX(), openRect.centerY(), 3500);
    sleep(60000);
    back();
    sleep(3500);
    back();
    sleep(3500);
}

/**
 * 领取红包操作
 */
function takeRedPack(num) {
    if (num >= 5) return;
    num += 1;
    let redPacks = className('android.widget.FrameLayout').find();
    for (let i = 0; i < redPacks.length; i++) {
        let pack = redPacks[i];
        let packChild = pack.children();
        for (let j = 0; j < packChild.length; j++) {
            let child = packChild[j];
            if (child != null) {
                let childText = child.text();
                if (childText != null && childText.indexOf("看视频抢红包") != -1) {
                    //是能领取的红包
                    watchVideoAndTakePack(child);
                }
            }
        }
    }
    takeRedPack(num);
}

/**
 * 在控制台输出
 * @param {string} context 
 */
function outputMessage(context) {
    toastLog(context);
}

function checkExistsById(id) {
    let ret = idEndsWith(id).findOnce();
    return ret == null ? false : true;
}

function coordinateClick(x, y, duration) {
    click(x, y);
    sleep(duration);
    return;
}

/**
 * 杀死app
 */
function killApp() {
    home();
    sleep(1500);
    app.openAppSetting(PACKAGE_NAME);
    text('一起来养猪').waitFor();
    sleep(4500);
    let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
    if (is_sure.enabled()) {
        let close = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
        if (close != null) {
            let rect = close.bounds();
            click(rect.centerX(), rect.centerY());
            sleep(3500);
        }
        close = textMatches(/(确定|强行停止)/).findOnce();
        log(close)
        if (close != null) {
            let rect = close.bounds();
            click(rect.centerX(), rect.centerY());
            sleep(1500);
        }
        sleep(1000);
        back();
    } else {
        back();
    }
    home();
    sleep(2500);
}

/**
 * 划动屏幕寻找控件
 */
function swipePage() {
    let start_x = device.width / 2;
    let start_y = device.height / 2;
    let end_x = device.width / 2;
    let end_y = device.height;

    gesture(300, [start_x, start_y], [end_x, end_y]);
    sleep(2000);
}

function turnplate() {
    let plate = idEndsWith(':id/fl_defense').findOnce();
    if (plate == null) throw new Error('找不到转盘');
    let plateRect = plate.bounds();

    coordinateClick(plateRect.centerX(), plateRect.centerY(), 3500);

}

/**
 * 合成猪
 */
function merge() {
    let mergeButton = idEndsWith(':id/fl_merge').findOnce();
    if (mergeButton == null) throw new Error('找不到合成按钮');
    let mergeRect = mergeButton.bounds();
    coordinateClick(mergeRect.centerX(), mergeRect.centerY(), 3500);
    let openButton = textEndsWith('看视频开启').findOnce();
    if (openButton == null) throw new Error('找不到开启按钮');
    let openRect = openButton.bounds();
    coordinateClick(openRect.centerX(), openRect.centerY(), 3500);
    sleep(60000);
    back();
    sleep(1500);
    let no = 280;
    while (no > 0) {
        no -= 1;
        let actButton = idEndsWith(':id/fl_tab').findOnce();
        if (actButton != null) {
            actRect = actButton.bounds();
            coordinateClick(actRect.centerX(), actRect.centerY(), 1000);
        }
    }
}

function countDown() {
    threads.start(function () {
        let no = 3600;
        while (no > 0) {
            no -= 1;
            sleep(1000);
        }
        throw new Error('该去合成猪了');
    });
}